/*
File:		Enemy.cpp
Author:		Ben Feldmann
Purpose:	Base class for game enemies
*/

#include "Enemy.h"
#include "SGD Wrappers\CSGD_TextureManager.h"
#include "EventSystem.h"
#include "GamePlayState.h"
#include "Level.h"
#include "Room.h"

Enemy::Enemy() 
{
	//EventSystem::GetInstance()->RegisterClient("target_hit", this);

	type = OBJ_ENEMY;

	player = GamePlayState::GetInstance()->GetPlayer();
	if( player )
		player->AddRef();

	stunned			= 0;
	stunTimer		= 0;
	slowTimer		= 0;
	prevSpeed		= 0;
	slowDuration	= 0;
	dotTimer		= 0;
	dotRate			= 0;
	curDot			= 0;
	dotDuration		= 0;
	dotDamage		= 0;
	slowed			= false;
	disabled		= false;

	deathEm  = Emitter::LoadEmitter("Emitters/enemyDeath.xml");
	damageEm = Emitter::LoadEmitter("Emitters/enemyHit.xml");
	dotEm    = Emitter::LoadEmitter("Emitters/enemyDOT.xml");
	stunEm   = Emitter::LoadEmitter("Emitters/enemyStun.xml");

	em = EmitterManager::GetInstance();

	stunEm->Loop(true);
	dotEm->Loop(true);

}

Enemy::~Enemy()
{
	if( player )
		player->Release();

	if( GetHealth() <= 0 )
		em->FireBurstEmitter(deathEm);

	damageEm->Shutdown();
	dotEm->Shutdown();
	stunEm->Shutdown();
}

void Enemy::Update(float elapsed)
{
	dotTimer += elapsed;

	if(slowed)
	{
		slowTimer += elapsed;
		if(slowTimer >= slowDuration)
		{
			slowed = false;
			SetSpeed(prevSpeed);
		}
	}
	if(dotTimer >= curDot && dotTimer <= dotDuration)
	{
		curDot += dotRate;
		EventSystem::GetInstance()->SendEvent("target_hit", this, new float(dotDamage));
	}
	if(disabled == true)
	{
		stunTimer += elapsed;

		if(stunTimer > stunned)
		{
			disabled = false;
			stunTimer = 0.0f;
		}
	}

	// Update Positions
	deathEm->SetPosition(GetX()+(GetWidth()/2.0f), GetY()+(GetHeight()/2.0f));
	damageEm->SetPosition(GetX()+(GetWidth()/2.0f), GetY()+(GetHeight()/2.0f));
	dotEm->SetPosition(GetX()+(GetWidth()/2.0f), GetY()+(GetHeight()/2.0f));
	stunEm->SetPosition(GetX()+(GetWidth()/2.0f), GetY()+(GetHeight()/2.0f));

	// Update Emiiters
	deathEm->Update(elapsed);
	damageEm->Update(elapsed);
	dotEm->Update(elapsed);
	stunEm->Update(elapsed);

	if( GetHealth() <= 0 )
	{
		GamePlayState::GetInstance()->GetLevel()->GetRoom(roomNum)->RemoveEnemy(this);
		return;
	}


}

void Enemy::Render()
{
	if(disabled == true)
		stunEm->Render();
	//damageEm->Render();
	if(dotTimer < dotDuration)
		dotEm->Render();

	if(damageEm->IsBursting())
	{
		damageEm->Render();
	}
}

RECT Enemy::GetRect()
{
	return Entity::GetRect();
}

void Enemy::Attack() { }

void Enemy::HandleEvent(Event* thisEvent) { }